package com.gopay.checkorder.service.impl.expay;
import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.SpdbConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.spdb.expay.SpdbMessageExPay;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.ExPayInteractRemoteService;

public class CheckOrderSpdbExPayImpl implements BankOrderService{
	
	private final static Logger logger = LoggerFactory.getLogger("SPDB");

	 @Resource(name = "bankExPayClient")
	 private ExPayInteractRemoteService bankExPayClient;

	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());

		SpdbMessageExPay base = new SpdbMessageExPay();
		base.setOrderId(bankOrder.getOrderId());
		base.setBankOrderId(bankOrder.getOutOrderId());
		base.setBank(BankConstants.BANK_LOGO_SPDB);
		base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
		
		Result result = new Result();
		try {
			result = bankExPayClient.queryOrder(base);
			if (result == null || !result.isSuccess()) {
				logger.error("bankClient fail.");
				if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				}
				logger.error(ToStringBuilder.reflectionToString(result,ToStringStyle.DEFAULT_STYLE));
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}
			if(StringUtils.isNotBlank(result.getBankRetCode())){
				//add by liuyu, 20170803, 快捷API失败通知
				bankOrder.setBankRespCode(result.getBankRetCode());
			}
				SpdbMessageExPay res = (SpdbMessageExPay) result.getDefaultModel();
				if (res == null) {
					// 查询订单为空
					logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
					checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
					checkOrderResult.setErrMsg("银行返回对账结果为空");
				}
			    if (StringUtils.isNotBlank(res.getErrorCode()) || StringUtils.isNotBlank(res.getErrorMsg())) {
					// 查询订单错误
					logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + res.getErrorCode() + " err:"+ res.getErrorMsg());
					checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
					checkOrderResult.setErrMsg(res.getErrorMsg());
					return checkOrderResult;
			    }else if(SpdbConstants.RESPCODE_SUCCESS.equals(res.getRespCode())){ //交易成功
			        logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，交易成功");
                    checkOrderResult.setSuccess(true);
                    InAccInfo accInfo = new InAccInfo();
                    accInfo.setOrderId(bankOrder.getOrderId());
                    accInfo.setAmount(new BigDecimal(res.getTranAmt()));
                    accInfo.setRetCode("00");
                    accInfo.setCardType(BankCardType.Unknown.toString());
                    checkOrderResult.setAccInfo(accInfo);
			    }else if(SpdbConstants.QUERY_PROCESSED.equals(res.getRespCode())){
			        logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getRespCode() + "，交易处理中");
                    checkOrderResult.setErrMsg("交易处理中");			    			    
				}else if ((SpdbConstants.CHECKORDER_FALSE.equals(res.getCompFlag()))) {// 交易失败
				    InAccInfo accInfo = new InAccInfo();
                    accInfo.setOrderId(bankOrder.getOrderId());
                    accInfo.setAmount(new BigDecimal(res.getTranAmt()));
                    accInfo.setRetCode("01");
                    accInfo.setCardType(BankCardType.Unknown.toString());
                    checkOrderResult.setAccInfo(accInfo);
					checkOrderResult.setBankFailure(true);
					logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，交易失败");
					checkOrderResult.setErrMsg("交易失败");
				}else if ((SpdbConstants.REVOKE_SUCCESS.equals(res.getCompFlag()))) {// 撤消成功
					logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，撤消成功");
					checkOrderResult.setErrMsg("撤消成功");
				}else if ((SpdbConstants.REFUND_PART.equals(res.getCompFlag()))) {// 部分退货
					logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，部分退货");
					checkOrderResult.setErrMsg("部分退货");
				}else if ((SpdbConstants.REFUND_ALL.equals(res.getCompFlag()))) {// 全部退货
					logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，全部退货");
					checkOrderResult.setErrMsg("全部退货");
				}else if ((SpdbConstants.AUTHORIZE_SUCCESS.equals(res.getCompFlag()))) {// 预授权确认成功
					logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，预授权确认成功");
					checkOrderResult.setErrMsg("预授权确认成功");
				}else if ((SpdbConstants.AUTHORIZE_FALSE.equals(res.getCompFlag()))) {// 预授权撤销成功
					logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，预授权撤销成功");
					checkOrderResult.setErrMsg("预授权撤销成功");
				}else if ((SpdbConstants.CHECKORDER_OTHER.equals(res.getCompFlag()))) {// 交易超时
					logger.error("浦发EXPAY订单" + bankOrder.getOrderId() + "交易状态为"+ res.getCompFlag() + "，交易超时");
					checkOrderResult.setErrMsg("交易超时");
				}											
			return checkOrderResult;
			
		} catch (Exception e) {
			logger.error("bankClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("对账调用bis失败");
			return checkOrderResult;
		}
	}


	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
